package com.xuanmiao.smsback.service.platform.operator.impl;

import com.panshi.hujin2.base.common.util.MD5Util;

import com.xuanmiao.smsback.common.enumtype.SecretKeyEnum;
import com.xuanmiao.smsback.common.enumtype.UserCreateTypeEnum;
import com.xuanmiao.smsback.common.enumtype.UserStatusEnum;

import com.xuanmiao.smsback.common.utils.AESUtil;
import com.xuanmiao.smsback.dao.mapper.BusinessPriceInfoMapper;
import com.xuanmiao.smsback.dao.mapper.UserAccountInfoMapper;
import com.xuanmiao.smsback.dao.model.UserAccountInfoDO;
import com.xuanmiao.smsback.domain.qo.UserInfoQO;
import com.panshi.hujin2.base.common.util.DozerUtils;
import com.panshi.hujin2.base.domain.page.Page;
import com.xuanmiao.smsback.dao.mapper.UserInfoMapper;
import com.xuanmiao.smsback.dao.model.UserInfoDO;

import com.xuanmiao.smsback.model.UserInfoBO;
import com.xuanmiao.smsback.service.platform.operator.UserInfoService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;


@Service
@Slf4j
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserAccountInfoMapper userAccountInfoMapper;
    @Autowired
    private BusinessPriceInfoMapper  businessPriceInfoMapper;
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void register(UserInfoBO userInfoBO) {

        // 校验注册账号是否存在
        if (existAccountNo(userInfoBO.getAccountNo())!=userInfoBO.getId()&&existAccountNo(userInfoBO.getAccountNo())!=null) {
            throw new RuntimeException("该用户名已存在");
        }
        // 密码解密，加密
        String password = null;
        try {
            // 原始密码

            String primitivePassword = AESUtil.decrypt(userInfoBO.getPassword(), SecretKeyEnum.AES_SECRET_KEY.getSecretKey());
            log.info("------------------------解密原始密码：{}",primitivePassword);
            // 随机盐加密
            password = MD5Util.generate(primitivePassword);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new RuntimeException("密码异常");
        }

        // 信息入库
        log.info("------------------------加密入库密码：{}",password);
        userInfoBO.setPassword(password);
        UserInfoDO userInfoDO = DozerUtils.convert(userInfoBO, UserInfoDO.class);
        userInfoDO.setIsMain(true);
        userInfoDO.setStatus(UserStatusEnum.SUBMIT_REGISTER.getCode());
        userInfoDO.setCreateType(UserCreateTypeEnum.PLATFORM_ADMIN_ADD.getCode());


        userInfoMapper.insertSelective(userInfoDO);

        UserInfoDO record = new UserInfoDO();
        record.setId(userInfoDO.getId());
        String businessNo = "SH" + String.format("%010d", Integer.valueOf(userInfoDO.getId()));
        record.setBusinessNo(businessNo);
        userInfoMapper.updateByPrimaryKeySelective(record);

        UserAccountInfoDO userAccountInfoDO = new UserAccountInfoDO();
        userAccountInfoDO.setId(userInfoDO.getId());
        userAccountInfoDO.setBalance(0.0);
        userAccountInfoDO.setCreditLimit(0.0);
        userAccountInfoMapper.insertSelective(userAccountInfoDO);

        userInfoMapper.add(userInfoDO);
        //增加报价
        businessPriceInfoMapper.add(userInfoDO);
    }
    @Override
    public Integer existAccountNo(String accountNo) {
        UserInfoQO userInfoQO = new UserInfoQO();
        userInfoQO.setAccountNo(accountNo);
        Integer res = userInfoMapper.selectIdByQO(userInfoQO);
        return res;
    }
    @Override
    public List<UserInfoBO> getList(UserInfoQO userInfoQO) {
        if(userInfoQO == null){
            userInfoQO = new UserInfoQO();
        }
        //获取数量
        Integer count = userInfoMapper.count(userInfoQO);
        Page page = userInfoQO.getPage();
        //设置总记录数
        page.setTotalNumber(count);
        List<UserInfoDO> userInfoDO = userInfoMapper.queryUserInfo(userInfoQO);
        List<UserInfoBO> listBOs = Collections.emptyList();
        if(userInfoDO!=null && userInfoDO.size()>0){
            listBOs = DozerUtils.convertList(userInfoDO, UserInfoBO.class);
            listBOs.forEach(listBO -> {
                listBO.setPassword("***");

            });
        }

        return listBOs;


    }

    @Override
    public UserInfoBO getById(Integer id) {

        return DozerUtils.convert(userInfoMapper.getById(id),UserInfoBO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(UserInfoBO userInfoBO) {

        if (userInfoBO.getPassword()!=null && userInfoBO.getPassword()!="") {
            String password = null;
            try {
                String newPassword = AESUtil.decrypt(userInfoBO.getPassword(), SecretKeyEnum.AES_SECRET_KEY.getSecretKey());
                // String newPassword = EncryptUtils.decryptByAES(SecretKeyEnum.AES_SECRET_KEY.getSecretKey(), userInfoBO.getPassword());
                password = MD5Util.generate(newPassword);

                userInfoBO.setPassword(password);
            } catch (Exception e) {
                throw new RuntimeException("修改密码失败");
            }
        }

        userInfoMapper.update(DozerUtils.convert(userInfoBO,UserInfoDO.class));
        userInfoMapper.add(DozerUtils.convert(userInfoBO,UserInfoDO.class));
    }

}



